import 'package:app_router_demo/customs/app_appbar.dart';
import 'package:app_router_demo/pages/home/home_list.dart';
import 'package:app_router_demo/pages/home/models/home_list_model.dart';
import 'package:auto_route/auto_route.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../config/app_router.dart';
import 'package:provider/provider.dart';
import '../../providers/home_tab_provider.dart';
import '../../providers/home_provider.dart';

@RoutePage()
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    // 移除这里延迟初始化TabController的代码，因为Provider将在MultiProvider中立即创建
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   Provider.of<HomeTabProvider>(
    //     context,
    //     listen: false,
    //   ).initializeTabController(this);
    // });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => HomeListProvider()),
        // 在这里创建 HomeTabProvider 并传递 TickerProvider
        ChangeNotifierProvider(create: (_) => HomeTabProvider(vsync: this)),
      ],
      child: Consumer2<HomeTabProvider, HomeListProvider>(
        builder: (context, tabProvider, listProvider, child) {
          return Scaffold(
            body: Stack(
              children: [
                // 背景图片
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  height: MediaQuery.of(context).size.width * 240 / 375.0,
                  child: Image.asset(
                    "assets/images/vz_sytop.png",
                    fit: BoxFit.cover,
                  ),
                ),
                // 主要内容
                SafeArea(
                  child: Column(
                    children: [
                      // 根据 _cards 是否为空来条件显示顶部卡片
                      if (tabProvider.cards.isNotEmpty) // 判断列表是否非空
                        _buildHorizontalGridView(tabProvider.cards, context),
                      // 顶部导航栏
                      _buildTopNavigationBar(tabProvider, listProvider),
                      // TabBarView内容
                      Expanded(
                        child: TabBarView(
                          controller: tabProvider.tabController,
                          children: const [HomeListPage(), HomeListPage()],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // 在您的代码中替换原有 ListView.separated
  Widget _buildHorizontalGridView(
    List<HomeTopCardModel> cardData,
    BuildContext content,
  ) {
    return Container(
      padding: EdgeInsets.only(top: 17, bottom: 15),
      height: (MediaQuery.of(context).size.width - 48) * 0.25 * 64 / 82.0 + 32,
      // width: (MediaQuery.of(context).size.width - 48) * 0.25,
      child: GridView.count(
        scrollDirection: Axis.horizontal,
        crossAxisCount: 1,
        childAspectRatio: 64 / 82,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        mainAxisSpacing: 8,
        children:
            cardData
                .map(
                  (data) => SizedBox(
                    child: CachedNetworkImage(
                      imageUrl: data.icon!,
                      placeholder:
                          (context, url) => Container(color: Color(0xfff8f8f8)),
                      fit: BoxFit.cover,
                    ),
                  ),
                )
                .toList(),
      ),
    );
  }

  Widget _buildTopNavigationBar(
    HomeTabProvider tabProvider,
    HomeListProvider listProvider,
  ) {
    return SizedBox(
      height: 44,
      child: Row(
        children: [
          // TabBar
          Expanded(
            child: TabBar(
              controller: tabProvider.tabController,
              isScrollable: true,
              tabAlignment: TabAlignment.start,
              labelPadding: const EdgeInsets.symmetric(horizontal: 16),
              indicatorSize: TabBarIndicatorSize.label,
              padding: EdgeInsets.zero,
              labelColor: const Color(0xFF313033),
              labelStyle: const TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.w500,
              ),
              unselectedLabelColor: const Color(0xFFB2B1B5),
              unselectedLabelStyle: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w400,
              ),
              indicator: const BoxDecoration(),
              dividerColor: Colors.transparent,
              tabs: tabProvider.tabs.map((tab) => Tab(text: tab)).toList(),
            ),
          ),
          // 右侧按钮
          _buildActionButtons(listProvider),
        ],
      ),
    );
  }

  Widget _buildActionButtons(HomeListProvider listProvider) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
          onPressed: () {
            // 搜索功能
            _showSearchDialog();
          },
          icon: const Icon(Icons.search, size: 24),
        ),
        IconButton(
          onPressed: () {
            listProvider.setIsList(!listProvider.isList);
          },
          icon: Image.asset(
            listProvider.isList
                ? 'assets/images/vhimg_sylb@3x.png'
                : "assets/images/vhing_syqh@3x.png",
            width: 24,
            height: 24,
          ),
        ),
      ],
    );
  }

  void _showSearchDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('搜索'),
            content: const TextField(
              decoration: InputDecoration(hintText: '请输入搜索内容'),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  // 执行搜索逻辑
                },
                child: const Text('搜索'),
              ),
            ],
          ),
    );
  }
}
